package com.example.service.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.UUID;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.common.ApiResult;
import com.example.entity.Video;
import com.example.mapper.VideoMapper;
import com.example.service.VideoService;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

@Service
public class VideoServiceImpl extends ServiceImpl<VideoMapper, Video> implements VideoService {
    @Resource
    private VideoMapper videoMapper;


    @Value("${web.windows.upload-path}")
    private String windowsSavePath;


    @Value("${web.linux.upload-path}")
    private String linuxSavePath;


    @Resource
    private Environment env;


    public ApiResult uploadAvatar(
            @RequestParam(required = false,value = "upFile") MultipartFile upFile, HttpServletRequest request){
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd/");
        if(upFile.isEmpty()) {
            return ApiResult.fail("您未选择任何文件！");
        }
        else {
            // 获取上传的文件名称，并结合存放路径，构建新的文件名称
            String originalFileName = upFile.getOriginalFilename();
            // 获取文件扩展名，扩展名不带“.”
            String fileSuffix = FileUtil.extName(originalFileName);

            String newFileName = UUID.randomUUID().toString().replace("-", "") + "." + fileSuffix;
            //限制文件类型
            if (! ( fileSuffix.equals("mp4") || fileSuffix.equals("avi") )) {
                return ApiResult.fail("仅支持上传.mp4、.avi视频格式！");
            }
            // 获取操作系统名称
            String osName = env.getProperty("os.name");
            File saveFile  = null;
            String format = sdf.format(new Date());
            if(osName.contains("Windows")) {
                saveFile = new File(windowsSavePath + format);
            }
            else {
                saveFile = new File(linuxSavePath + format);
            }
            // 如果服务器保存文件目录不存在，则创建
            if(saveFile != null && !saveFile.exists()) {
                saveFile.mkdirs();
            }
            try {
                upFile.transferTo(new File(saveFile,newFileName));
                String baseUrl = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + request.getContextPath();
                String imgUrl = baseUrl+ "/resource/"+ format + newFileName; // 客户端访问头像路径，也就是存储在数据库中路径
                return ApiResult.ok(imgUrl,"视频上传成功！");
            } catch (IOException e) {
                return ApiResult.fail("上传视频失败！");
            }
        }
    }

    @Override
    public Integer thumbVideo(Integer videoId) {
        return videoMapper.thumbVideo(videoId);
    }

    @Override
    public Integer addVideo(String videoTitle, MultipartFile videoUrl, Integer courseId,HttpServletRequest request) {
        ApiResult apiResult = uploadAvatar(videoUrl,request);
        if(apiResult.isSuccess()==true){
            String data = (String) apiResult.getData();
            Integer integer = videoMapper.addVideo(videoTitle, data, courseId);
        return integer;
    }else{
        return null;
        }
    }

    @Override
    public Page<Video> selectVideoPage(String name , Integer page, Integer size) {
        Page<Video> page1 = new Page<>(page, size);
        QueryWrapper queryWrapper = new QueryWrapper();
        queryWrapper.like("video_title",name) ;
        queryWrapper.orderByDesc("create_date");
        Page page2 = videoMapper.selectPage(page1, queryWrapper);
        return page2;
    }

    @Override
    public Integer deleteById(Integer id) {
        int i = videoMapper.deleteById(id);
        return i;
    }
}
